<template>
    <MyDialog ref="myDialog" :title="titleText" width="600px" :on-confirm="confirm" :on-cancel="clearData">
        <MyForm ref="myForm" :form-data="formData" :form-item-list="formItemList" :form-rules="formRules"
            :disabled=isDisabled></MyForm>
    </MyDialog>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus';
interface FormData {
    name: string;
    devlibVersion: string;
    description: string;
    file: MyComment.FormUploadValue;
}

const emit = defineEmits<{
    (event: 'complete', value: boolean): void;
}>();

const formData = ref<FormData>({
    name: '',
    devlibVersion: '',
    description: '',
    file: null,
});

let fileInfo = {
    fileId: '',
    sizeB: '',
    fileName: '',
    id: '',
};

const dialogMode = ref<string>('new');
const titleText = ref<string>('新增设备库');
const isDisabled = ref<boolean>(false);

const formItemList = ref<MyComment.FormItemProps<FormData>[]>([
    {
        prop: 'name',
        label: '设备库名称',
        contentProps: { maxlength: '20', placeholder: '请输入设备库名称' } as MyComment.FormItemContentProps['input'],
    },
    {
        prop: 'devlibVersion',
        label: '设备库版本',
        contentProps: { maxlength: 20, placeholder: '请输入设备库版本' } as MyComment.FormItemContentProps['input'],
    },
    {
        prop: 'description',
        label: '描述',
        contentProps: { maxlength: 100, placeholder: '请输入描述', type: 'textarea', resize: 'none', rows: 5 } as MyComment.FormItemContentProps['input'],
    },
    {
        prop: 'file',
        label: '设备库',
        type: 'upload',
        contentExtends: { placeholder: '请选择设备库文件，格式为zip,rar,7z', isShowDelete: !isDisabled.value } as MyComment.FormItemContentExtends['upload'],
    },
]);

const validateFileType = (_rule: any, value: string, callback: any) => {
    if (value && myForm.value) {
        const data = myForm.value.getData();
        const fileExtension = data.file?.name.split('.').pop()?.toLowerCase() ?? '';
        if (!['zip', 'rar', '7z'].includes(fileExtension)) {
            callback(new Error('仅支持 zip,rar,7z 格式'));
        }
    }
    callback();
}

const formRules: MyComment.FormRules<FormData> = {
    name: { required: true, trigger: 'blur', message: '请输入设备库名称' },
    devlibVersion: { required: true, trigger: 'blur', message: '请输入设备库版本' },
    file: [
        { required: true, trigger: 'blur', message: '请选择设备库文件' },
        { validator: validateFileType, trigger: 'change', message: '仅支持 zip,rar,7z 格式' }
    ],
};

const myDialog = ref<MyComment.DialogInstance>();
const myForm = ref<MyComment.FormInstance<FormData>>();
const editDeviceLibrary = async (data: any, fileId?: string) => {
    const editeRes = await MyService.resource.editeDeviceLibrary({
        id: fileInfo.id,
        fileId: fileId || fileInfo.fileId,
        sizeB: data.file.size || fileInfo.sizeB,
        name: data.name,
        devlibVersion: data.devlibVersion,
        description: data.description,
        fileName: data.file.name || fileInfo.fileName,
    });
    if (editeRes.code === 200) {
        ElMessage.success({
            message: '编辑成功'
        })
        emit('complete', true);
        return true;
    } else {
        ElMessage.error({
            message: editeRes.msg || '编辑失败',
        });
        emit('complete', false);
        return false;
    }
}
const confirm = async (): Promise<boolean> => {
    if (isDisabled.value) {
        return true;
    }
    let result = (await myForm.value?.validate()) || false;
    if (result) {
        const data = myForm.value?.getData();
        if (data?.file && data.file.name) {
            const res = await MyService.resource.getDeviceLibraryFileUploadUrl({ fileName: data.file.name || '' });
            if (res.code === 200 && res.data) {
                const uploadRes = await MyService.resource.updateDeviceLibraryFile({ fileId: res.data.fileId, file: data.file });
                if (uploadRes.code === 200) {
                    if (dialogMode.value === 'new') {
                        const createRes = await MyService.resource.createDeviceLibrary({
                            fileId: res.data.fileId,
                            sizeB: data.file.size.toString(),
                            name: data.name,
                            devlibVersion: data.devlibVersion,
                            description: data.description,
                            fileName: data.file.name,
                        });
                        if (createRes.code === 200) {
                            emit('complete', true);
                            return true;
                        } else {
                            ElMessage.error({
                                message: createRes.msg || '新增设备库失败',
                            });
                            emit('complete', false);
                            return false;
                        }
                    } else {
                        editDeviceLibrary(data, res.data.fileId);
                    }
                } else {
                    ElMessage.error({
                        message: uploadRes.msg || '上传文件失败',
                    });
                    emit('complete', false);
                    return false;
                }
            } else {
                ElMessage.error({
                    message: res.msg || '获取文件ID失败',
                });
                emit('complete', false);
                return false;
            }
        } else {
            editDeviceLibrary(data);
        }
    }
    return result;
};

const open = (val?: any) => {
    formData.value = {
        name: '',
        devlibVersion: '',
        description: '',
        file: null,
    }
    dialogMode.value = val?.mode || 'new';
    myForm.value?.clearValidate();
    isDisabled.value = val?.mode === 'detail' ? true : false;
    formItemList.value[3].contentExtends.isShowDelete = !isDisabled.value;
    titleText.value = val?.mode === 'detail' ? '查看设备库' : val?.mode === 'edit' ? '编辑设备库' : '新增设备库';
    if (val?.id) {
        getDetailInfo(val.id);
        return;
    }
    myDialog.value?.open();
};

const getDetailInfo = async (id: string) => {
    const res: any = await MyService.resource.getDeviceLibraryDetailInfo({ deviceId: id });
    if (res.code === 200) {
        fileInfo = res.data;
        formData.value.name = res.data.name;
        formData.value.devlibVersion = res.data.libVersion;
        formData.value.description = res.data.description;
        formData.value.file = res.data.fileName;
        myDialog.value?.open();
    } else {
        ElMessage.error({
            message: res.msg,
        });
    }
}

const clearData = () => {
    myForm.value?.clearData();
};

defineExpose({
    open,
});
</script>

<style scoped></style>
